package com.mirror.tk.core.module.sys.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Timer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mirror.tk.core.module.sms.domain.SmsTpl;
import com.mirror.tk.core.module.sms.service.SmsTplService;
import com.mirror.tk.core.module.sys.domain.SysDictionaries;
import com.mirror.tk.core.module.sys.domain.SysProperty;
import com.mirror.tk.core.module.sys.dto.DictionariesDto;
import com.mirror.tk.core.module.sys.dto.PropertyDto;
import com.mirror.tk.core.module.sys.dto.SmsTplDto;
import com.mirror.tk.core.module.sys.service.BasicService;
import com.mirror.tk.core.module.sys.service.SysDictionariesService;
import com.mirror.tk.core.module.sys.service.SysPropertyService;
import com.mirror.tk.framework.common.exception.BusinessException;
import com.mirror.tk.framework.utils.Collections3;

public class BasicServiceImpl implements BasicService {

	@Value("${load.basic.data:true}")
	private String loadBasicData;
	
	private static final Logger logger = LogManager.getLogger(BasicServiceImpl.class);	
	// 全局变量缓存
	private Map<String, DictionariesDto> dicCache = Maps.newHashMap();
	// 全局变量缓存
	private Map<String, PropertyDto> proCache = Maps.newHashMap();
	// 全局变量缓存
	private Map<String, SmsTplDto> smsCache = Maps.newHashMap();
	
	private SysPropertyService sysPropertyService;
	private SysDictionariesService sysDictionariesService;
	private SmsTplService smsTplService;
	
	private Integer reloadinterval = 60; //每隔60秒，重新初始化一次
	private Timer timer;
	
	/**
     * 初始化方法
     * @throws Exception
     */
	@Override
    public void init() {
		logger.info("BasicServiceImpl--->启动加载公用字典数据 ");
		
		this.reloadsetting();
//		timer = new Timer();
//		
//		timer.schedule(new TimerTask() {
//			public void run() {
//				reloadsetting();
//			}
//		},reloadinterval*1000, reloadinterval*1000);
//
//		try {
//			if (loadBasicData.equalsIgnoreCase("true")) {
//				
//			}
//		} catch (Exception e) {
//			logger.error("BasicServiceImpl--->启动加载数据--->异常", e);
//		}
		logger.info("BasicServiceImpl--->结束加载公用字典数据 ");

	}
    
    /**
     * 销毁
     * @throws Exception
     */
	@Override
	public void destroy() {
		timer.cancel();
		timer = null;
	}

	/**
	 * 全局配置重置
	 */
	@Override
	public void reloadsetting(){
		// 获取全部配置信息
		logger.debug("==========初始化全局配置信息开始=============");
		List<SysProperty> list = sysPropertyService.getAll();
		if(null != list && !list.isEmpty()){
			for (SysProperty sp : list) {
				PropertyDto dto = new PropertyDto();
				dto.setProKey(sp.getProKey());
				dto.setProValue(sp.getProValue());
				proCache.put(dto.getProKey(), dto);
			}
		}
		logger.debug("==========初始化全局配置信息结束=============");
	}
	
	@Override
    public String getProValue(String key) {
		PropertyDto dto = proCache.get(key);
		if(null == dto){
			SysProperty property = sysPropertyService.findByProKey(key);
			if(null == property){
				throw new BusinessException("未找到系统参数[" + key + "]，请确认参数存在！");
			}
			dto = new PropertyDto();
			dto.setProKey(property.getProKey());
			dto.setProValue(property.getProValue());
			proCache.put(dto.getProKey(), dto);
		}
		return dto.getProValue();
    }

	@Override
	public String getSmsTpl(String code) {
		SmsTplDto dto = smsCache.get(code);
		if(null == dto){
			SmsTpl smsTpl = smsTplService.getByName(code);
			if(null == smsTpl){
				throw new BusinessException("未找到短信模板[" + code + "]，请确认短信模板存在！");
			}
			dto = new SmsTplDto();
			dto.setSmsKey(smsTpl.getName());
			dto.setSmsValue(smsTpl.getTpl());
			smsCache.put(smsTpl.getName(), dto);
		}
		return dto.getSmsValue();
	}
	
	@Override
	public DictionariesDto getDictionariesDto(String key) {
		DictionariesDto dto = dicCache.get(key);
		if(null == dto){
			SysDictionaries dictionaries = sysDictionariesService.findByKey(key);
			if(null == dictionaries){
				throw new BusinessException("未找到字典数据[" + key + "]，请确认字典数据存在！");
			}
			dto = SysDictionaries2Dto(dictionaries);
			dicCache.put(key, dto);
		}
		return dto;
	}
	
	/**
	 * 系统字典对像转dto对像
	 * <p>Description:</p>
	 * @param dictionaries
	 * @return
	 * @author fengshi on 2016年12月9日
	 */
	private DictionariesDto SysDictionaries2Dto(SysDictionaries dictionaries){
		DictionariesDto dto = new DictionariesDto();
		dto.setId(dictionaries.getId());
		dto.setParentId(dictionaries.getParentId());
		dto.setDicKey(dictionaries.getKey());
		dto.setDicValue(dictionaries.getValue());
		dto.setType(dictionaries.getType());
		dto.setDescription(dictionaries.getDescription());
		if(Collections3.isNotEmpty(dictionaries.getSubList())){
			List<DictionariesDto> subList = Lists.newArrayList();
			for (SysDictionaries dic : dictionaries.getSubList()) {
				subList.add(SysDictionaries2Dto(dic));
			}
			dto.setSubList(subList);
		}
		return dto;
	}

	
	public SysPropertyService getSysPropertyService() {
		return sysPropertyService;
	}

	public void setSysPropertyService(SysPropertyService sysPropertyService) {
		this.sysPropertyService = sysPropertyService;
	}

	public SysDictionariesService getSysDictionariesService() {
		return sysDictionariesService;
	}

	public void setSysDictionariesService(SysDictionariesService sysDictionariesService) {
		this.sysDictionariesService = sysDictionariesService;
	}

	public SmsTplService getSmsTplService() {
		return smsTplService;
	}

	public void setSmsTplService(SmsTplService smsTplService) {
		this.smsTplService = smsTplService;
	}

}
